package com.tvserials.notification;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.google.android.gms.common.AccountPicker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.tvserials.notification.services.NotificationService;
import com.tvserials.notification.services.ServiceFactory;
import com.tvserials.notification.utils.DisplayToastMessage;

/**
 * Created by Alex on 26.04.2014.
 */
public class LoginActivity extends AccountAuthenticatorActivity {
    static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
    public static final String PARAM_USER_PASS = "pass";
    public static final String ARG_IS_ADDING_NEW_ACCOUNT = "IS_ADDING_ACCOUNT";
    public static final String ACCOUNT_TYPE = "com.serials";
    public static final String AUTHTOKEN_TYPE = "tokenType";
    private EditText usernameText;
    private EditText passwordText;
    private NotificationService integrationService;
    private AccountManager mAccountManager;
    private SignInButton signInButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        usernameText = (EditText) findViewById(R.id.usernameText);
        passwordText = (EditText) findViewById(R.id.passwordText);
        signInButton = (SignInButton) findViewById(R.id.btnGmail);
        signInButton.setSize(SignInButton.SIZE_WIDE);
        signInButton.setOnClickListener(new SignClickListener());

        mAccountManager = AccountManager.get(this);
    }

    public void login(View view) {
        String username = usernameText.getText().toString();
        String password = passwordText.getText().toString();
        if (!username.isEmpty() && !password.isEmpty()) {
            new RegisterAsyncTask().execute();
        } else {
            runOnUiThread(new DisplayToastMessage(getApplicationContext(), R.string.no_username_or_password_message));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
            Bundle extras = data.getExtras();
        }
    }

    private void finishLogin(Intent intent) {
        String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
        final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
        if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
            String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
            // Creating the account on the device and setting the auth token we got
            // (Not setting the auth token will cause another call to the server to authenticate the user)
            mAccountManager.addAccountExplicitly(account, accountPassword, null);
            mAccountManager.setAuthToken(account, AUTHTOKEN_TYPE, authtoken);
        } else {
            mAccountManager.setPassword(account, accountPassword);
        }
        activateSyncAdapter(accountName);
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * Activate sync adapter with default interval
     *
     * @param userName
     */
    private void activateSyncAdapter(String userName) {
        Account account = new Account(userName, LoginActivity.ACCOUNT_TYPE);
        int uploadInterval = 15;
        long triggerAtMillis = uploadInterval * 60;
        ContentResolver.addPeriodicSync(account, MainAppActivity.AUTHORITY, new Bundle(), triggerAtMillis);
        ContentResolver.setSyncAutomatically(account, MainAppActivity.AUTHORITY, true);
    }

    public void forgot(View view) {
    }

    /**
     * Starts an activity in Google Play Services so the user can pick an account
     */
    private void pickUserAccount() {
        String[] accountTypes = new String[]{"com.google"};
        Intent intent = AccountPicker.newChooseAccountIntent(null, null,
                accountTypes, false, null, null, null, null);
        startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
    }

    private class RegisterAsyncTask extends AsyncTask<Void, Void, Intent> {

        @Override
        protected Intent doInBackground(Void... params) {
            String userName = usernameText.getText().toString();
            String userPass = passwordText.getText().toString();
            integrationService = ServiceFactory.getNotificationService();
            String authtoken = integrationService.userSignIn(userName, userPass);
            final Intent res = new Intent();
            res.putExtra(AccountManager.KEY_ACCOUNT_NAME, userName);
            res.putExtra(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
            res.putExtra(AccountManager.KEY_AUTHTOKEN, authtoken);
            res.putExtra(PARAM_USER_PASS, userPass);
            return res;
        }

        @Override
        protected void onPostExecute(Intent intent) {
            finishLogin(intent);
        }
    }

    private class SignClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
            if (status == ConnectionResult.SUCCESS) {
                pickUserAccount();
            } else {
                Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(status, LoginActivity.this, 1);
                errorDialog.show();
            }
        }
    }
}
